﻿using XfTechOAWeb.Data;
using XfTechOAWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EFCore.Extensions;         //引用老师定义的扩展方法的命名空间
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System.Data;
using MySqlConnector;
using XfTechOAWeb.EFCore.Base;
using XfTechOAWeb.Infrastructure.Utilities;

namespace XfTechOAWeb.EFCore
{
    /// <summary>
    /// 用户模块仓储
    /// </summary>
    public class UserRepository : EfBaseRepository<User>, IUserRepository
    {
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db">上下文注入</param>
        public UserRepository(DbContext db) : base(db)
        {
            _db = db;
        }

        /// <summary>
        /// 加载用户菜单
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public IEnumerable<dynamic> LoadUserMenu(int userid)
        {
            //判断数据库类型，因为数据库不同，存储过程的参数不同
            if (AppConfigurtaionServices.Configuration["SqlType"] == "MySql")
            {
                MySqlParameter p1 = new MySqlParameter("_userId", userid);

                //调用存储过程
                var list = this.QueryFromProc("p_getUserMenu", p1); //传参
                return list;
            }
            else if (AppConfigurtaionServices.Configuration["SqlType"] == "SqlServer")
            {
                SqlParameter p1 = new SqlParameter("@userId", userid);

                //调用存储过程
                var list = this.QueryFromProc("p_getUserMenu", p1); //传参
                return list;
            }
            else
            {
                return null;
            }
            
        }

        /// <summary>
        /// 给用户添加角色
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="rid"></param>
        /// <returns></returns>
        public int AddUserRole(int uid, string rid)
        {
            //方法一、直接用EF的对象方法
            var list = _db.Set<UserRole>().Where(x => x.UserId == uid).ToList();
            if (list != null)
            {
                _db.Set<UserRole>().RemoveRange(list);
            }
            var srid = rid.Split(',');
            List<UserRole> userRoles = new List<UserRole>();
            srid.ToList().ForEach(x =>
            {
                userRoles.Add(new UserRole() { RoleId = Convert.ToInt32(x), UserId = uid });
            });
            _db.Set<UserRole>().AddRange(userRoles);

            return _db.SaveChanges();

            //方法二、调用存储过程
            //SqlParameter[] paras = new SqlParameter[]
            //{
            //   new SqlParameter("@uid",uid),
            //   new SqlParameter("@rids", rid)
            //};

            //return _db.ExecuteNonQuery("proc_addUserRole", //存储过程的名字
            //                          System.Data.CommandType.StoredProcedure, //命令类型为存储过程
            //                          paras); //传参

            //方法三、开启事务+执行sql语句
            //using (var tran = _db.Database.BeginTransaction())
            //{
            //    try
            //    {
            //        int affectRows = _db.Database.ExecuteSqlInterpolated($"delete from UserRoles where UserId={uid}");

            //        rid.Split(',').ToList().ForEach(roleid =>
            //        {
            //            affectRows += _db.Database.ExecuteSqlInterpolated(
            //                                    $"insert into UserRoles values( {uid},{roleid})"
            //                                );
            //        });

            //        tran.Commit();
            //        return affectRows; //返回受影响行数
            //    }
            //    catch (Exception ex)
            //    {
            //        //记录日志
            //        tran.Rollback();
            //        return -1;
            //    }
            //}
        }
    }
}
